from django.conf import settings
from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from .constants import ACCESS_TOKEN_EXPIRES


def generate_access_token(openid):
    """
    签名,序列化openid
    :param openid: 用户的openid
    :return: access_token
    """
    # 创建序列化对象
    s = Serializer(settings.SECRET_KEY,ACCESS_TOKEN_EXPIRES)
    data = {'openid': openid}
    token = s.dumps(data)
    # 将生成的token解码返回
    return token.decode()


def check_access_token(access_token):
    """
    反序列化签名并检验签名
    """
    s = Serializer(settings.SECRET_KEY, ACCESS_TOKEN_EXPIRES)
    try:
        data = s.loads(access_token)
    except BadData:
        return None
    else:
        return data.get('openid')
